const db = require('../db')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../config')
const R = require('../response')

// 用户路由处理模块
exports.registerUser = (req, res) => {
    // 获取用户传递的信息
    const userInfo = req.body
    // 查询邮箱是否存在
    const emailSql = 'select * from tb_user where email = ?'
    db.query(emailSql, userInfo.email, (err, results) => {
        if (err) {
            return res.send(new R(1, err.message))
        }
        if (results.length > 0) {
            return res.send(new R(1, '邮箱已被注册,请稍后重试!'))
        }
        // 插入新用户
        const insertSql = 'insert into tb_user set ?'
        // 密码加密处理
        userInfo.password = bcrypt.hashSync(userInfo.password, 10)
        db.query(insertSql, { email: userInfo.email, nickname: userInfo.nickname, password: userInfo.password, createdAt: new Date() }, (err, results) => {
            if (err) {
                return res.send(new R(1, err.message))
            }
            if (results.affectedRows !== 1) {
                return res.send(new R(1, '注册失败,请稍后重试!'))
            }
            return res.send(new R(0, '注册用户成功!'))
        })
    })
}

exports.loginUser = (req, res) => {
    const userInfo = req.body
    // 查看邮箱存不存在
    const emailSql = 'select * from tb_user where email = ?'
    db.query(emailSql, userInfo.email, (err, results) => {
        if (err) {
            return res.send(new R(1, err.message))
        }
        if (results.length === 0) {
            return res.send(new R(1, '邮箱不存在!'))
        }
        // 比较密码是否正确
        if (!bcrypt.compareSync(userInfo.password, results[0].password)) {
            return res.send(new R(1, '密码错误,请稍后重试!'))
        }
        // 登录成功,生成token
        const user = { ...results[0], password: '', avatar: '' }
        const token = jwt.sign(user, config.jwtSecretKey, {
            expiresIn: config.expireIn
        })
        return res.send(new R(0, '登录成功!', 'Bearer ' + token))
    })
}

exports.getUserInfo = (req, res) => {
    // 获取用户，排除密码信息
    const sqlStr = 'select id, email, nickname, avatar, description from tb_user where id = ?'
    db.query(sqlStr, req.user.id, (err, results) => {
        if (err) {
            return res.send(new R(1, err.message))
        }
        if (results.length === 0) {
            return res.send(new R(1, '获取用户信息失败!'))
        }
        return res.send(new R(0, '获取用户信息成功!', results[0]))
    })
}

exports.updateUser = (req, res) => {
    // 更新用户信息
    const updateStr = 'update tb_user set ? where id = ?'
    db.query(updateStr, [req.body, req.body.id], (err, results) => {
        if (err) {
            return res.send(new R(1, err.message))
        }
        if (results.affectedRows !== 1) {
            return res.send(new R(1, '更新用户信息失败!'))
        }
        return res.send(new R(0, '更新用户信息成功!'))
    })
}